package cn.edu.zut.hhr.interceptor;

import cn.edu.zut.hhr.entity.User;
import cn.edu.zut.hhr.utils.JwtUtil;
import cn.edu.zut.hhr.utils.RedisUtil;
import cn.edu.zut.hhr.utils.UserUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Order(5000)
public class UserInterceptor implements HandlerInterceptor {

    @Resource
    RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if(token != null){
            User user = null;
            String username = JwtUtil.verifyToken(token).get("username").toString();
            if(username != null){
                Object o = redisUtil.get("username_"+username);
                if(o != null){
                    try{
                        user = JSON.parseObject(o.toString(),User.class);
                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
            if(user != null){
                UserUtil.set(user);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserUtil.del();
    }
}
